<template>
	<el-card class="upload-news">
		<div style="border: 1px solid #ccc">
			<Toolbar
					style="border-bottom: 1px solid #ccc"
					:editor="editorRef"
					:defaultConfig="toolbarConfig"
					:mode="mode"
			/>
			<Editor
			        style="height: 500px;width: 200px; overflow-y: hidden;"
			        v-model="valueHtml"
			        :defaultConfig="editorConfig"
			        :mode="mode"
			        @onCreated="handleCreated"
			      />
		</div>
		<div class="footer">
			<el-button type="info" @click="cancelHandler">取消操作</el-button>
			<el-button type="warning" @click="clearHandler">清空内容</el-button>
			<el-button type="primary" @click="uploadNews">{{ isEditor ? '修改新闻' : '发布新闻' }}</el-button>
		</div>
		<dialog-vue v-model="visible"
		            title="添加新闻"
		            :base-info="isEditor ? newsInfo : null"
		            @validateSuccess="successHandler"
		/>
	</el-card>
</template>

<script setup>
import getConf from './conf'
import {nanoid} from 'nanoid'
import {useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import {getNewsById} from "@/api/news";
import DialogVue from './components/dialog'
import {IS_ADD, IS_EDITOR} from "@/constant";
import '@wangeditor/editor/dist/css/style.css'
import {uploadNewsApi, updateNews} from '@/api/news'
import {useRouter, onBeforeRouteLeave} from "vue-router";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {onBeforeUnmount, ref, shallowRef, computed, onActivated, nextTick} from 'vue'

const editorRef = shallowRef()
const visible = ref(false)
const valueHtml = ref('')
const toolbarConfig = {}
const FILE_LIST = []
const mode = 'default'

const getFilename = (src) => {
	const reg = /^[\s\S]+\/static\/([\s\S]+)$/
	const srcExec = reg.exec(src)
	if (srcExec) {
		return srcExec[1]
	}
}

const editorConfig = {
	placeholder: '请输入新闻内容...',
	MENU_CONF: getConf(
			(src) => {
				const name = getFilename(src)
				if (name) {
					FILE_LIST.push(name)
				}
			},
	),
}

const getEditorImagesAndVideo = () => {
	return [...editorRef.value.getElemsByType('image'), ...editorRef.value.getElemsByType('video')].map(item => {
		const {src} = item
		return getFilename(src)
	}).filter(Boolean)
}

const getImage = () => {
	const images = [...editorRef.value.getElemsByType('image'), ...editorRef.value.getElemsByType('video')].map(item => {
		const {src} = item
		return getFilename(src)
	}).filter(Boolean)
	return FILE_LIST.filter(item => !images.includes(item))
}

const isEditor = computed(() => {
	return route.query.id
})
const route = useRoute();
const newsInfo = ref({
	title: '',
	desc: '',
	imgSrc: '',
	date: '',
	id: '',
	news_id: '',
	category: '',
})
const initNewsInfo = (target) => {
	newsInfo.value = {...target}
}
const initNews = async (_id) => {
	const {success, data} = await getNewsById(_id)
	if (!success) {
		console.log('数据获取失败!')
		return
	}
	const {content, news_desc, news_title, news_time, preview, id, news_id, category_id} = data;
	editorRef.value.setHtml(content);
	initNewsInfo({
		title: news_title,
		desc: news_desc,
		date: news_time,
		imgSrc: preview,
		id,
		news_id,
		category: category_id,
	})
	await nextTick(() => {
		updateImageCache()
	})
}

onActivated(() => {
	console.log(FILE_LIST)
	if (!isEditor.value) {
		return
	}
	initNews(isEditor.value)
})
onBeforeRouteLeave((to, from, next) => {
	if (isEditor.value) {
		editorRef.value.clear()
	}
	next()
})
const router = useRouter()
const cancelHandler = () => {
	if (isEditor.value) {
		router.push({name: 'newsManage'}).catch(() => null)
	}
	editorRef.value.clear()
}
const handleCreated = (editor) => {
	editorRef.value = editor // 记录 editor 实例，重要！
}

const uploadNews = () => {
	if (editorRef.value.isEmpty()) {
		ElMessage({
			type: 'warning',
			message: '请输入新闻的内容!',
			duration: 1500,
		})
		return
	}
	visible.value = true
}

const updateImageCache = () => {
	const images = [...editorRef.value.getElemsByType('image'), ...editorRef.value.getElemsByType('video')].map(item => {
		const {src} = item
		return getFilename(src)
	}).filter(Boolean)
	FILE_LIST.length = 0
	FILE_LIST.push(...images)
}

const successHandler = async ({title, date, desc, imgSrc, type, category}) => {
	if (type === IS_EDITOR && isEditor.value) {
		const {id, news_id} = newsInfo.value
		const dif = getImage()
		const {success, data} = await updateNews({
			id, newsId: news_id, desc, title, preview: imgSrc, content: valueHtml.value, date, category, dif
		})
		initNewsInfo({
			title: data['news_title'],
			desc: data['news_desc'],
			date: data['news_time'],
			imgSrc: data.preview,
			id: data.id,
			news_id: data.news_id,
			category: data['category_id'],
		})
		if (!success) {
			console.log('新闻更新失败')
			return
		}
		visible.value = false
		// 更新 图片依赖
		updateImageCache()
	}
	if (type === IS_ADD && !isEditor.value) {
		// 获取用户删除的图片
		const dif = getImage()
		const {success} = await uploadNewsApi({
			title,
			time: date,
			desc,
			content: valueHtml.value,
			author: '默认作者',
			id: nanoid(15),
			preview: imgSrc,
			dif,
			category,
		})
		if (!success) {
			console.log('新闻上传失败!')
			return
		}
		visible.value = false;
		FILE_LIST.length = 0
		editorRef.value.blur();
		editorRef.value.clear()
		await nextTick(() => {
			updateImageCache()
		})
	}
}

const clearHandler = () => {
	editorRef.value.clear()
}
onBeforeUnmount(() => {
	const editor = editorRef.value
	if (editor === null) return
	editor.destroy()
})

</script>

<style scoped lang="scss">
.upload-news {
	.footer {
		display: flex;
		justify-content: flex-end;
		box-sizing: border-box;
		gap: 20px;
		margin-top: 20px;
	}
}
</style>